package com.example.administrator.nurse.present;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.nurse.R;
import com.example.administrator.nurse.base.BaseActivity;
import com.example.administrator.nurse.common;
import com.example.administrator.nurse.model.CommonViewHolder;
import com.example.administrator.nurse.model.RecyclerViewCommonAdapter;
import com.example.administrator.nurse.model.bean.OrderActivityBean;
import com.example.administrator.nurse.util.recyclerViewHelper;
import com.example.administrator.nurse.widget.LoginInputEdit;
import com.example.administrator.nurse.widget.SearchInput;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/30.
 *
 */

public class OrderActivity extends BaseActivity {

    private recyclerViewHelper recyclerViewHelper;
    private SearchInput SearchInput;
    private RecyclerViewCommonAdapter adapter;
    private List<OrderActivityBean> list = new ArrayList<>();
    private final int[] colors = new int[]{
            R.drawable.chengse,
            R.drawable.lvse,
            R.drawable.lansv,
            R.drawable.red
    };
    private int lid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        getData(false,null);
    }

    private final int GetDataNormal = 0x11;
    private final int GetDataMore   = 0x12;
    private void getData(boolean loadMore,String isSearch){
        startLoadingDialog();
        RequestParams requestParams = new RequestParams();
        requestParams.put("method",selectIndex);
        requestParams.put("id",common.nId);
        requestParams.put("sort",sortSelect);
        if(isSearch!=null){
            requestParams.put("con",isSearch);
        }else{
            SearchInput.searchInput.setText("");
        }
        List<String> l = new ArrayList<>();
        switch (typeSelect){
            case -1:
                l.add("全部");
                break;
            case 0:
                l.add("长期单");
                break;
            case 1:
                l.add("新开单");
                break;
            case 2:
                l.add("临时单");
                break;
            case 3:
                l.add("新停单");
                break;
        }
        if(sortSelect==0){
            l.add("时间升序");
        }else{
            l.add("时间降序");
        }
        if(typeSelect!=-1){
            requestParams.put("type",typeSelect);
        }
        if(loadMore){
            requestParams.put("lid",lid); /** 加载更多的 id */
            doPost(GetDataMore, l, common.Host + "/Controller/orderController.php?func=getOrderData", requestParams);
        }else {
            doPost(GetDataNormal, l, common.Host + "/Controller/orderController.php?func=getOrderData", requestParams);
        }
    }

    @Override
    protected int setLayotId() {
        return R.layout.order_main;
    }

    @Override
    protected void onFailure(int requestCode, Object object, String errorMsg) {
        stopLoadingDialog();
        Log.d("zzzzz","errorMsg");
    }

    @Override
    protected void onSuccess(int requestCode, Object object, String response) {
        stopLoadingDialog();
        Log.d("zzzzz",response);
        switch (requestCode){
            case GetDataNormal:
                recyclerViewHelper.getRecyclerView().refreshComplete();
                if(response.trim().equals("0")){
                    t("暂无医嘱记录!");
                    list.clear();
                    adapter.notifyDataSetChanged();
                    userTestData(); /** 数据库没数据，使用测试数据，日后可以删除 */
                }else {
                    t(response);
                    List<String> l = (List<String>) object;
                    Log.d("zzzzz",l.get(0));
                    SearchInput.type.setText(l.get(0));
                    SearchInput.sort.setText(l.get(1));
                    dealDataJson(response, false);
                }
                break;
            case GetDataMore:
                recyclerViewHelper.getRecyclerView().loadMoreComplete();
                List<String> l = (List<String>) object;
                SearchInput.type.setText(l.get(0));
                SearchInput.sort.setText(l.get(1));
                dealDataJson(response,true);
                break;
        }
    }

    private void dealDataJson(String response,boolean isLoadMore){
        if(response!=null){
            try{
                JSONArray jsonArray = new JSONArray(response);
                int length = jsonArray.length();
                if(length>0 && !isLoadMore){
                    list.clear();
                }
                for(int i=0;i<length;i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    OrderActivityBean bean = new OrderActivityBean();
                    bean.setArea(getJSONValue(jsonObject, "numOfRoom") + "区号");

                    bean.setContent(getJSONValue(jsonObject, "content"));
                    bean.setHospital(getJSONValue(jsonObject, "hn"));
                    bean.setUrl(getJSONValue(jsonObject, "urlOfPortrait"));
                    bean.setStartTime(getJSONValue(jsonObject, "startTime"));
                    bean.setOverTime(getJSONValue(jsonObject, "overTime"));

                    bean.setInfo(
                            getJSONValue(jsonObject, "name") + "," +
                            (getJSONValue(jsonObject, "sex").trim().equals("1")?"男":"女") + "," +
                            getJSONValue(jsonObject, "age")+"岁" + ","
                    );
                    bean.setDoc(getJSONValue(jsonObject, "doctor"));
                    bean.setBed(getJSONValue(jsonObject, "numOfBed")+"床号");
                    int type = getJSONINTValue(jsonObject, "type");
                    switch (type){
                        case 0:
                            bean.setDan("长期单");
                            break;
                        case 1:
                            bean.setDan("新开单");
                            break;
                        case 2:
                            bean.setDan("临时单");
                            break;
                        case 3:
                            bean.setDan("新停单");
                            break;
                    }
                    String temp = getJSONValue(jsonObject, "executeTime").trim();
                    if(temp.equals("移动护士")){
                        bean.setTime("暂无");
                        bean.setIsDo("现在未执行");
                    }else{
                        bean.setTime(temp);
                        bean.setIsDo("现在已执行");
                    }
                    if(selectIndex==0){
                        bean.setThatDo("当日未执行");
                    }else if(selectIndex==1){
                        bean.setThatDo("当日已执行");
                    }else if(selectIndex==2){
                        bean.setThatDo("1");
                    }
                    if(i==length-1){
                        lid = getJSONINTValue(jsonObject, "id");
                    }
                    list.add(bean);
                }
                adapter.notifyDataSetChanged();
            }catch (Exception e){
                Log.d("zzzzz",e.toString());
            }
        }
    }

    private int typeSelect=-1,sortSelect=0;
    private View selectTemp = null; /** 选择中间值 */
    private int selectIndex = 1; /** 默认第二个,0,1,2 */
    private void initView() {
        configCommonHeader(OrderActivity.this, getResources().getString(R.string.order_title), 0);
        //listView= (ListView) findViewById(R.id.order_list);
        LinearLayout container = (LinearLayout) findViewById(R.id.container);
        /** 添加选择模块 */
        final View DayFinish  = LayoutInflater.from(this).inflate(R.layout.select_item, (ViewGroup) getWindow().getDecorView(),false);
        DayFinish.setTag(0);
        container.addView(DayFinish);

        final View DayNot     = LayoutInflater.from(this).inflate(R.layout.select_item, (ViewGroup) getWindow().getDecorView(),false);
        DayNot.setTag(1);
        ((TextView)DayNot.findViewById(R.id.text)).setText("当日已执行");
        DayNot.findViewById(R.id.line).setVisibility(View.VISIBLE); /** 显示出颜色 */
        ((TextView)DayNot.findViewById(R.id.text)).setTextColor(getResources().getColor(R.color.navbar)); /** 显示颜色 */
        selectTemp = DayNot;
        container.addView(DayNot);

        final View DayHistory = LayoutInflater.from(this).inflate(R.layout.select_item, (ViewGroup) getWindow().getDecorView(),false);
        DayHistory.setTag(2);
        ((TextView)DayHistory.findViewById(R.id.text)).setText("执行记录");
        container.addView(DayHistory);

        onItemSelectListener(DayFinish, DayNot, DayHistory);

        initAdapter();
        //initRecyclerView();

        recyclerViewHelper = new recyclerViewHelper(this, (XRecyclerView) findViewById(R.id.recyclerView))
                .withAdapter(adapter)
                .withLayoutManager(null)
                .withPullRefrshOpen(true)
                .withRefresh(new recyclerViewHelper.refreshListener() {
                    @Override
                    public void refresh() {
                        getData(false,null);
                    }
                })
                .withLoadMore(new recyclerViewHelper.loadMoreListener() {
                    @Override
                    public void loadMore() {
                        getData(true,null);
                    }
                }).initRecyclerView()
        ;

        SearchInput = new SearchInput(this,f(R.id.search_common))
                .withTypeMenu(R.menu.type)
                .withSortMenu(R.menu.sort)
                .withMenuItemClickListener(new SearchInput.OnMenuItemClickListener() {
                    @Override
                    public void menuTypeItemClick(MenuItem item) { // 类型下拉点击
                        switch (item.getItemId()) {
                            case R.id.first:
                                typeSelect = 0;
                                break;
                            case R.id.second:
                                typeSelect = 1;
                                break;
                            case R.id.third:
                                typeSelect = 2;
                                break;
                            case R.id.fourth:
                                typeSelect = 3;
                                break;
                            case R.id.five:
                                typeSelect = -1;
                                break;
                        }
                        getData(false,null);
                    }

                    @Override
                    public void menuSortItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.first:
                                sortSelect = 0;
                                break;
                            case R.id.second:
                                sortSelect = 1;
                                break;
                        }
                        getData(false,null);
                    }
                })
                .withSearchClickListener(new SearchInput.OnSearchClickListener() {
                    @Override
                    public void searchClick(LoginInputEdit searchInput) {
                        if (searchInput.isOk("搜索关键字不能少于1个")) {
                            getData(false, searchInput.getStringText());
                        }
                    }
                })
                .init();

    }

    private void userTestData(){
        /** 测试数据 */
        for(int i=0;i<20;i++){
            OrderActivityBean bean = new OrderActivityBean();
            bean.setArea("0"+i+"病区");
            bean.setBed("0"+i+"病床");
            bean.setDan("临时单");
            bean.setInfo("王小二,女，68岁");
            bean.setDoc("黄华佗");
            bean.setTime("2016-3-"+i+"12:12:"+i);
            bean.setIsDo("未执行");
            list.add(bean);
        }
        adapter.notifyDataSetChanged();
    }

    private void initAdapter(){

        adapter = new RecyclerViewCommonAdapter(this,list) {

            @Override
            protected int getLayoutId() {
                return R.layout.order_activity_bean_layout;
            }

            @Override
            protected void bindView(CommonViewHolder holder, final int position) {

                LinearLayout firstFather;
                TextView area,bed,dan,info,doc,time,isDo,isThatDo;

                firstFather = holder.getLinearLayout(R.id.firstFather);
                area = holder.getTextView(R.id.area);
                bed = holder.getTextView(R.id.bed);
                dan = holder.getTextView(R.id.dan);
                info = holder.getTextView(R.id.info);
                doc = holder.getTextView(R.id.doc);
                time = holder.getTextView(R.id.time);
                isDo = holder.getTextView(R.id.isDo);
                isThatDo = holder.getTextView(R.id.isThatDo);

                firstFather.setBackgroundResource(colors[position%4]);
                if(list.get(position).getThatDo().equals("1")){
                    isThatDo.setVisibility(View.GONE);
                }else {
                    isThatDo.setText(list.get(position).getThatDo());
                }
                area.setText(list.get(position).getArea());
                bed.setText(list.get(position).getBed());
                dan.setText(list.get(position).getDan());
                info.setText(list.get(position).getInfo());
                doc.setText(list.get(position).getDoc());
                time.setText(list.get(position).getTime());
                isDo.setText(list.get(position).getIsDo());

                holder.getRelativeLayout(R.id.bean_father).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onItemClickListener.onItemClick(null, position);
                    }
                });

                firstFather.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            }
        };

        adapter.setOnItemClickListener(new RecyclerViewCommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(OrderActivity.this, OrderInfoActivity.class);
                intent.putExtra("data",list.get(position));
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }

    private void onItemSelectListener(final View... view){ /** 个数动态变化 */
        for(final View viewT : view){
            viewT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(selectTemp!=null){
                        /** 处理上一个被选中的 */
                        ((TextView)selectTemp.findViewById(R.id.text)).setTextColor(Color.GRAY);
                        selectTemp.findViewById(R.id.line).setVisibility(View.GONE);
                    }
                    selectTemp = viewT;
                    ((TextView)viewT.findViewById(R.id.text)).setTextColor(getResources().getColor(R.color.navbar)); /** 显示颜色 */
                    viewT.findViewById(R.id.line).setVisibility(View.VISIBLE); /** 显示出颜色 */
                    /** 下面标记 */
                    selectIndex = (Integer)viewT.getTag();
                    getData(false,null);
                }
            });
        }
    }
}
